package com.depth.viewer.facade.bindableproxy
{
	import com.depth.viewer.utils.Util;
	
	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayCollection;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class ArrayCollectionBindableProxy extends Proxy implements IDataBindableProxy
	{
		[Bindable]
		private var _data:ArrayCollection;
		public function ArrayCollectionBindableProxy(proxyName:String=null)
		{
			super(proxyName);
			_data = new ArrayCollection();
			setData(_data);
		}
		public function get(id:String):Object{
			for each(var item:Object in getData()){
				if(item.id == id){
					return item;
				}
			}
			return null;
		}
		public function refresh(item:Object = null):void
		{
			var ac:ArrayCollection = getData() as ArrayCollection;
			if(item){
				ac.itemUpdated(item);
			}else{
				for each(var itemObj:Object in ac){
					ac.itemUpdated(itemObj);
				}
			}
		}
		
		public function updata(id:String, item:Object):void
		{
			for each(var itemObj:Object in getData()){
				if(itemObj.id == id){
					Util.copyProperty(itemObj,item);
					refresh(item);
				}
			}
		}
		
		public function remove(id:String):void
		{
			for each(var itemObj:Object in getData()){
				if(itemObj.id == id){
					var ri:int = _data.getItemIndex(itemObj);
					_data.removeItemAt(ri);
					refresh(itemObj);
				}
			}
		}
		public function clear():void{
			_data.removeAll();
			refresh();
		}
		public function add(item:Object,index:int = -1):void
		{
			if(index != -1){
				_data.addItemAt(item,index);
			}else{
				_data.addItem(item);	
			}			
			refresh(item);
		}
		public function get size():int{
			return _data.length;
		}
		public function binding(site:Object):void
		{
			BindingUtils.bindProperty(site,"dataProvider",this,_data);
		}
	}
}